'''
Created on Jul 18, 2012

@author: thomas_dao
'''

from google.appengine.api import memcache
from google.appengine.ext import ndb
from entity.entity import Vote
import logging

@ndb.tasklet
def get_vote_stats_async(article_key):
    qry_up = Vote.query(Vote.article == article_key, Vote.up == True)
    qry_down = Vote.query(Vote.article == article_key, Vote.up == False)
    (vote_up, vote_down) = yield (qry_up.count_async(limit=10000), 
                                  qry_down.count_async(limit=10000))
    raise ndb.Return(vote_up, vote_down)



@ndb.tasklet
def save_stats_async(article_key):
    """
    Save all statistics into article
    """
    # Construct memcache keys
    (vote_up, vote_down) = yield get_vote_stats_async(article_key)
    logging.info("vote " + str(vote_up) + "--" + str(vote_down) + "--" + str(article_key.id()))
    mem_key_up = article_key.urlsafe() + "vote_up"
    mem_key_down = article_key.urlsafe() + "vote_down"
    mem_key_view = article_key.urlsafe() + "views"
    mem_key_comment = article_key.urlsafe() + "comments"
    
    client = memcache.Client()
    
    # Get value from memcache
    if not vote_up:
        vote_up = 0
        
    if not vote_down:
        vote_down = 0
        
    views = client.get(mem_key_view)
    if not views:
        views = 0
        
    comments = client.get(mem_key_comment)
    if not comments:
        comments = 0
        
    # Set attributes for article
    article = article_key.get()
    article.vote_up = vote_up
    article.vote_down = vote_down
    article.views = article.views + views
    article.comments = article.comments + comments
    article.put()
    
    # Reset memcache value
    client.set(mem_key_down, 0)
    client.set(mem_key_up, 0)
    client.set(mem_key_view, 0)
    client.set(mem_key_comment, 0)